//
//  ZYCPublishCircleFriendsViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/9/19.
//

#import "ZYCPublishCircleFriendsViewController.h"
#import "ZYCPublishCircleFriendsView.h"
#import <TZImagePickerController.h>
#import "ZYCGrowthFileModel.h"
#import "ZYCLoginOutView.h"
#import <MobileCoreServices/MobileCoreServices.h>
@interface ZYCPublishCircleFriendsViewController ()<UINavigationControllerDelegate,ZYCPublishCircleFriendsViewDelegate,ZYCLoginOutViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) ZYCPublishCircleFriendsView *publishView;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, strong) NSMutableArray * selectedPhotos;
@property (nonatomic, strong) NSMutableArray * selectedAssets;
@property (nonatomic, assign) NSUInteger updateImageCount;
@property (nonatomic, strong) NSMutableArray *updateImageResults;
@property (nonatomic, strong) ZYCLoginOutView *loginOutView;
@property (strong, nonatomic) CLLocation *location;
@end

@implementation ZYCPublishCircleFriendsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self.view addSubview:self.publishView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

#pragma mark - ZYCPublishCircleFriendsViewDelegate
- (void)publishCircleFriendsViewDidCancel{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)publishCircleFriendsViewDidComfirm{

    [self.loginOutView show];
}


- (void)ClickPublishGrowthFileAction{
    self.updateImageCount = 0;
    self.updateImageResults = [NSMutableArray arrayWithCapacity:0];
    
    if (self.publishView.selectedPhotos.count > 0) {
        for (UIImage *image in self.publishView.selectedPhotos) {
            self.updateImageCount ++;
            [self uploadWithImage:image];
        }
    }else{
        [self publishGrowthFile];
    }
    

}

- (void)publishGrowthFile{
    if (self.updateImageCount != 0) {// 防止发布多条
        return;
    }
    
    if (self.publishView.content.length == 0 && self.updateImageResults.count == 0) {
        [MrjToast makeToast:@"请输入内容" makeView:self.view];
        return;
    }
    
    NSDictionary *params = @{
        @"grade":self.model.grade,
        @"classId":self.model.classId,
        @"stuUserId":self.model.userId,
        @"content":self.publishView.content ? self.publishView.content : @"",
        @"busFileList":self.updateImageResults,
        @"identityType":@"0"
    };
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_AddGrowthReport requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                [MrjSVProgressHUD showSuccessWithStatus:responseObject[@"body"]];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self dismissViewControllerAnimated:YES completion:nil];
                });
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}
- (void)uploadWithImage:(UIImage *)image{
    NSString *urlStr = [NSString stringWithFormat:@"%@/zd-system-service/%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],Common_Post_Upload];
    [[URLManager sharedURLManager] POST:urlStr parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSString *fileName;
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"MMddHHmmss";
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        fileName = [NSString stringWithFormat:@"%@.png",dateString];//以这种格式防止上传的图片重复覆盖
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                self.updateImageCount --;
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                NSString *filePath = responseObject[@"body"][@"url"];
                NSString *fileName = responseObject[@"body"][@"fileName"];
                [dict setObject:filePath forKey:@"filePath"];
                [dict setObject:fileName forKey:@"fileName"];
                [self.updateImageResults addObject:dict];
                
                [self publishGrowthFile];
            }else{
                [MrjToast makeToast:@"图片上传失败" makeView:self.view];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        }];
}


- (void)publishCircleFriendsViewDidAddPhoto{
    [self presentFliter];
}

- (void)presentFliter{
    ZYCWeakSelf
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf pushTZImagePickerViewController];

    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:photoAction];
    [alert addAction:albumAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)takePhoto{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }

}
// 调用相机
- (void)pushImagePickerController {
    // 提前定位
    __weak typeof(self) weakSelf = self;
    [[TZLocationManager manager] startLocationWithSuccessBlock:^(NSArray<CLLocation *> *locations) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = [locations firstObject];
    } failureBlock:^(NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.location = nil;
    }];
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        NSMutableArray *mediaTypes = [NSMutableArray array];
        [mediaTypes addObject:(NSString *)kUTTypeImage];
        if (mediaTypes.count) {
            _imagePickerVc.mediaTypes = mediaTypes;
        }
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

- (void)pushTZImagePickerViewController{
    ZYCWeakSelf
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 columnNumber:3 delegate:self pushPhotoPickerVc:YES];
    if (self.publishView.selectedAssets.count > 0) {
        imagePickerVc.selectedAssets = self.publishView.selectedAssets;
    }
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        weakSelf.selectedPhotos = [NSMutableArray arrayWithArray:photos];
        weakSelf.selectedAssets = [NSMutableArray arrayWithArray:assets];
        weakSelf.publishView.selectedAssets = self.selectedAssets;
        weakSelf.publishView.selectedPhotos = self.selectedPhotos;
    }];
     imagePickerVc.barItemTextColor = [UIColor blackColor];
     [imagePickerVc.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor blackColor]}];
    imagePickerVc.allowPickingVideo = NO;
     imagePickerVc.navigationBar.tintColor = [UIColor blackColor];
     imagePickerVc.naviBgColor = [UIColor whiteColor];
     imagePickerVc.navigationBar.translucent = NO;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}


#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSDictionary *meta = [info objectForKey:UIImagePickerControllerMediaMetadata];
        [[TZImageManager manager] savePhotoWithImage:image meta:meta location:self.location completion:^(PHAsset *asset, NSError *error){
            [tzImagePickerVc hideProgressHUD];
            if (error) {
                NSLog(@"图片保存失败 %@",error);
            } else {
                TZAssetModel *assetModel = [[TZImageManager manager] createModelWithAsset:asset];
                [self refreshCollectionViewWithAddedAsset:assetModel.asset image:image];
            }
        }];

    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)refreshCollectionViewWithAddedAsset:(PHAsset *)asset image:(UIImage *)image {
    [self.selectedAssets addObject:asset];
    [self.selectedPhotos addObject:image];
    self.publishView.selectedAssets = self.selectedAssets;
    self.publishView.selectedPhotos = self.selectedPhotos;
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
    self.navigationController.delegate = self;
}




#pragma mark - ZYCLoginOutViewDelegate
- (void)loginOutViewDidClickLogout{
    [self ClickPublishGrowthFileAction];
}

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
 
    }
    return _imagePickerVc;
}
- (NSMutableArray *)selectedPhotos {
    if (!_selectedPhotos) {
        _selectedPhotos = [[NSMutableArray alloc] init];
    }
    return _selectedPhotos;
}

- (NSMutableArray *)selectedAssets {
    if (!_selectedAssets) {
        _selectedAssets = [[NSMutableArray alloc] init];
    }
    return _selectedAssets;
}

- (ZYCLoginOutView *)loginOutView {
    if (!_loginOutView) {
        _loginOutView = [[ZYCLoginOutView alloc] initWithFrame:CGRectMake(0, 0, 280.0f, 155.0f)];
        _loginOutView.delegate = self;
        _loginOutView.title = @"温馨提示";
        _loginOutView.content = @"确认是否发布";
        [self.navigationController.view addSubview:_loginOutView];
    }
    return _loginOutView;
}


- (ZYCPublishCircleFriendsView *)publishView {
    if (!_publishView) {
        _publishView = [[ZYCPublishCircleFriendsView alloc] initWithFrame:self.view.bounds];
        _publishView.delegate = self;
    }
    return _publishView;
}



- (void)dealloc{

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
